<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="160px">
     <el-form-item label="项目编号" prop="projectNum">
            <el-select :disabled="isEditMode"
                v-model="dataForm.projectNum"
                placeholder="请选择项目编号" @change="getProductInfo()"
                class="label_len">
              <el-option
                  v-for="item in projectList"
                  :key="item.prProjectNumber"
                  :label="item.prProjectNumber + ' ' + item.prProjectName"
                  :value="item.prProjectNumber" >
              </el-option>
            </el-select>
          </el-form-item>
    <el-form-item label="样机编号" prop="prototypeNum">
      <el-input v-model="dataForm.prototypeNum" placeholder="样机编号"></el-input>
    </el-form-item>
    <el-form-item label="样机型号" prop="prototypeModel">
      <el-input v-model="dataForm.prototypeModel" placeholder="样机型号"></el-input>
    </el-form-item>
    <el-form-item label="测定地点" prop="testLocation">
      <el-input v-model="dataForm.testLocation" placeholder="测定地点"></el-input>
    </el-form-item>
    <el-form-item label="检查日期" prop="testDate">
      <el-date-picker
        v-model="dataForm.testDate"
        type="date" format="yyyy-MM-dd" @change="handleDateChange"
        placeholder="选择检查日期">
      </el-date-picker>
    </el-form-item>
    <el-form-item label="试验地（长*宽）m" prop="testLengthWidth">
      <el-input 
        v-model="dataForm.testLength" 
        placeholder="长 (m)" 
        style="width: 48%; display: inline-block;">
      </el-input>
      <span style="margin: 0 10px;">X</span>
      <el-input 
        v-model="dataForm.testWidth" 
        placeholder="宽 (m)" 
        style="width: 48%; display: inline-block;">
      </el-input>
    </el-form-item>
    <el-form-item label="前茬作物名称" prop="previousCropName">
      <el-input v-model="dataForm.previousCropName" placeholder="前茬作物名称"></el-input>
    </el-form-item>
    
      <el-collapse>
        <el-collapse-item v-for="(point, index) in measurementData" :key="index" :name="'point' + index"  >
          <template #title>
            <div style="display: flex; align-items: center;margin-left:100px" >
              <span style="margin-right: 20px;text-align:center">{{ point.point }}</span>
            </div>
          </template>
          <div v-for="n in 10" :key="n" style="margin-left:100px">
            <el-input type=Number v-model="point['value' + n]" :placeholder="'请输入值 ' + n" style="width:700px"/>
          </div>
        </el-collapse-item>
      </el-collapse>
    
    <el-form-item label="平均值" prop="shavg">
      <el-input v-model="averageValue" placeholder="平均值" ></el-input>
    </el-form-item>
    <el-form-item label="杂草或绿肥种类" prop="wgmtypes">
      <el-input v-model="dataForm.wgmtypes" placeholder="杂草或绿肥种类"></el-input>
    </el-form-item>
     <el-collapse>
      <el-collapse-item v-for="(point, index) in measurementData2" :key="index" :name="'point2' + index">
        <template #title>
          <div style="display: flex; align-items: center;margin-left:100px" >
              <span style="margin-right: 20px;text-align:center">{{ point.point }}</span>
            </div>
        </template>
        <div v-for="n in 10" :key="n" style="margin-left:100px">
          <el-input type=Number v-model="point['value' + n]" :placeholder="'请输入值 ' + n" style="width:700px"/>
        </div>
      </el-collapse-item>
    </el-collapse>
    <el-form-item label="高度平均值" prop="havg">
      <el-input v-model="heightAverageValue" placeholder="高度平均值" ></el-input>
    </el-form-item>
    <el-form-item label="耕作深度" prop="cultivationDepth">
      <el-input v-model="dataForm.cultivationDepth" placeholder="耕作深度"></el-input>
    </el-form-item>
    <el-form-item label="土壤类型" prop="soilType">
      <el-select v-model="dataForm.soilType" placeholder="请选择土壤类型">
        <el-option label="砂土" value="砂土"></el-option>
        <el-option label="黏土" value="黏土"></el-option>
        <el-option label="壤土" value="壤土"></el-option>
      </el-select>
    </el-form-item>


    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        measurementData: Array.from({ length: 3 }, (v, i) => ({
          point: `测点${i + 1}`,
          value1: '',
          value2: '',
          value3: '',
          value4: '',
          value5: '',
          value6: '',
          value7: '',
          value8: '',
          value9: '',
          value10: ''
        })),
        measurementData2: Array.from({ length: 3 }, (v, i) => ({
          point: `测点${i + 1}`,
          value1: '',
          value2: '',
          value3: '',
          value4: '',
          value5: '',
          value6: '',
          value7: '',
          value8: '',
          value9: '',
          value10: ''
        })),
        visible: false,
        dataForm: {
          id: 0,
          prototypeNum: '',
          prototypeModel: '',
          testLocation: '',
          testDate: '',
          projectNum: '',
          testLengthWidth: '',
          previousCropName: '',
          stubbleHeight: '',
          shavg: '',
          wgmtypes: '',
          height: '',
          havg: '',
          cultivationDepth: '',
          soilType: '',
          inspectorName: '',
          recordName: '',
          checkerName: '',
          creatorId: '',
          testLength: '', 
          testWidth: ''   
        },
        projectList: [],
        isEditMode: false,
        dataRule: {
          prototypeNum: [
            { required: true, message: '样机编号不能为空', trigger: 'blur' }
          ],
          prototypeModel: [
            { required: true, message: '样机型号不能为空', trigger: 'blur' }
          ],
          testLocation: [
            { required: true, message: '测定地点不能为空', trigger: 'blur' }
          ],
          testDate: [
            { required: true, message: '测定日期不能为空', trigger: 'blur' }
          ],
          projectNum: [
            { required: true, message: '项目编号不能为空', trigger: 'blur' }
          ],
          testLengthWidth: [
            { required: true, message: '试验地（长*宽）m不能为空', trigger: 'blur' }
          ],
          testLength: [
            { required: true, message: '试验地（长）m不能为空', trigger: 'blur' }
          ],
          testWidth: [
            { required: true, message: '试验地（宽）m不能为空', trigger: 'blur' }
          ],
          previousCropName: [
            { required: true, message: '前茬作物名称不能为空', trigger: 'blur' }
          ],
          stubbleHeight: [
            { required: true, message: '留茬高度不能为空', trigger: 'blur' }
          ],

          wgmtypes: [
            { required: true, message: '杂草或绿肥种类不能为空', trigger: 'blur' }
          ],
          height: [
            { required: true, message: '高度cm不能为空', trigger: 'blur' }
          ],

          cultivationDepth: [
            { required: true, message: '耕作深度不能为空', trigger: 'blur' }
          ],
          soilType: [
            { required: true, message: '土壤类型不能为空', trigger: 'blur' }
          ],
          inspectorName: [
            { required: true, message: '检测人姓名不能为空', trigger: 'blur' }
          ],
          recordName: [
            { required: true, message: '记录人姓名不能为空', trigger: 'blur' }
          ],
          checkerName: [
            { required: true, message: '校核人姓名不能为空', trigger: 'blur' }
          ],
          creatorId: [
            { required: true, message: '创建人id不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    computed: {
    averageValue() {
      let total = 0;
      let count = 0;

      this.measurementData.forEach(point => {
        for (let n = 1; n <= 10; n++) {
          const value = Number(point['value' + n]);
          if (!isNaN(value)) {
            total += value;
            count++;
          }
        }
      });

      return count > 0 ? (total / count).toFixed(2) : 0;
    },
    heightAverageValue() {
      let total = 0;
      let count = 0;

      this.measurementData2.forEach(point => {
        for (let n = 1; n <= 10; n++) {
          const value = Number(point['value' + n]);
          if (!isNaN(value)) {
            total += value;
            count++;
          }
        }
      });

      return count > 0 ? (total / count).toFixed(2) : 0;
    }
  },
   watch: {
    averageValue(newVal) {
      this.dataForm.shavg = newVal; // 将计算结果赋值给 dataForm.shavg
    },
    heightAverageValue(newVal) {
      this.dataForm.havg = newVal; // 将计算结果赋值给 dataForm.havg
    }
  },
  mounted (){
    this.getprojectList()
  },
    methods: {
      //获取项目列表
      getprojectList() {
        this.$http({
          url: this.$http.adornUrl(`/reportapproval/product/getProjectNumber`),
          method: 'post',
          data: this.$http.adornData({
          })
        }).then((data) => {
          if (data && data.code === 0) {
            console.log(data.productList)
            this.projectList = data.productList
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      getProductInfo(){
        this.$http({
          url: this.$http.adornUrl(`/reportapproval/product/getProductInfo/${this.dataForm.projectNum}`),
          method: 'get',
          data: this.$http.adornParams({})
        }).then((data) => {
          if (data && data.code === 0) {
            this.dataForm.prototypeNum = data.productInfo.prProjectNumber
            this.dataForm.prototypeModel = data.productInfo.prProducerModel

          }else {
            this.$message.error(data.msg)
          }
        })
      },
       handleDateChange(value) {
        if (value) {
          // 将选择的日期转换为 UTC 字符串
          const date = new Date(value);
          const utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
          this.dataForm.testDate = utcDate.toISOString();
        }
      },
      init (id) {
        this.isEditMode = false;
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/reportapproval/experimenttalinvestigationrecord/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then((data) => {
              if (data && data.code === 0) {
                this.isEditMode =true;
                const stubbleHeightData=JSON.parse(data.experimenttalInvestigationRecord.stubbleHeight)
                const heightData=JSON.parse(data.experimenttalInvestigationRecord.height)
                this.measurementData = Array.from({ length: 3 }, (v, i) => {
                  const pointKey = `测点${i + 1}`;
                  const values = stubbleHeightData[pointKey] || []; // 获取对应测点的值，如果不存在则为一个空数组
                  return {
                      point: pointKey,
                      value1: values[0] || '',
                      value2: values[1] || '',
                      value3: values[2] || '',
                      value4: values[3] || '',
                      value5: values[4] || '',
                      value6: values[5] || '',
                      value7: values[6] || '',
                      value8: values[7] || '',
                      value9: values[8] || '',
                      value10: values[9] || ''
                  };
                });
                this.measurementData2 = Array.from({ length: 3 }, (v, i) => {
                 const pointKey = `测点${i + 1}`;
                 const values = heightData[pointKey] || []; // 获取对应测点的值，如果不存在则为一个空数组
                
                  return {
                      point: pointKey,
                      value1: values[0] || '',
                      value2: values[1] || '',
                      value3: values[2] || '',
                      value4: values[3] || '',
                      value5: values[4] || '',
                      value6: values[5] || '',
                      value7: values[6] || '',
                      value8: values[7] || '',
                      value9: values[8] || '',
                      value10: values[9] || ''
                  };
                });

                this.dataForm.prototypeNum = data.experimenttalInvestigationRecord.prototypeNum
                this.dataForm.prototypeModel = data.experimenttalInvestigationRecord.prototypeModel
                this.dataForm.testLocation = data.experimenttalInvestigationRecord.testLocation
                this.dataForm.testDate = data.experimenttalInvestigationRecord.testDate
                this.dataForm.projectNum = data.experimenttalInvestigationRecord.projectNum
                if (data.experimenttalInvestigationRecord.testLengthWidth) {
                  const [length, width] = data.experimenttalInvestigationRecord.testLengthWidth.split('X'); // 分割字符串
                  this.dataForm.testLength = length; // 回显长
                  this.dataForm.testWidth = width;   // 回显宽
                }
                this.dataForm.testLengthWidth = data.experimenttalInvestigationRecord.testLengthWidth
                this.dataForm.previousCropName = data.experimenttalInvestigationRecord.previousCropName
                
                this.dataForm.shavg = data.experimenttalInvestigationRecord.shavg
                this.dataForm.wgmtypes = data.experimenttalInvestigationRecord.wgmtypes
                
                this.dataForm.havg = data.experimenttalInvestigationRecord.havg
                this.dataForm.cultivationDepth = data.experimenttalInvestigationRecord.cultivationDepth
                this.dataForm.soilType = data.experimenttalInvestigationRecord.soilType
                this.dataForm.inspectorName = data.experimenttalInvestigationRecord.inspectorName
                this.dataForm.recordName = data.experimenttalInvestigationRecord.recordName
                this.dataForm.checkerName = data.experimenttalInvestigationRecord.checkerName
                this.dataForm.creatorId = data.experimenttalInvestigationRecord.creatorId
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        const stubbleHeight = {};
        const height = {};
         // 组合长和宽为 "长*宽" 的格式
        this.dataForm.testLengthWidth = `${this.dataForm.testLength}X${this.dataForm.testWidth}`;

        // 处理第一组数据
        this.measurementData.forEach(point => {
          stubbleHeight[point.point] = [];
          for (let n = 1; n <= 10; n++) {
            stubbleHeight[point.point].push(point['value' + n]);
          }
        });

        // 处理第二组数据
        this.measurementData2.forEach(point => {
          height[point.point] = [];
          for (let n = 1; n <= 10; n++) {
            height[point.point].push(point['value' + n]);
          }
        });
      

        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/reportapproval/experimenttalinvestigationrecord/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'prototypeNum': this.dataForm.prototypeNum,
                'prototypeModel': this.dataForm.prototypeModel,
                'testLocation': this.dataForm.testLocation,
                'testDate': new Date(this.dataForm.testDate).toISOString().split('T')[0],
                'projectNum': this.dataForm.projectNum,
                'testLengthWidth': this.dataForm.testLengthWidth,
                'previousCropName': this.dataForm.previousCropName,
                'stubbleHeight': JSON.stringify(stubbleHeight),
                'shavg': this.dataForm.shavg,
                'wgmtypes': this.dataForm.wgmtypes,
                'height': JSON.stringify(height),
                'havg': this.dataForm.havg,
                'cultivationDepth': this.dataForm.cultivationDepth,
                'soilType': this.dataForm.soilType,
                'inspectorName': this.dataForm.inspectorName,
                'recordName': this.dataForm.recordName,
                'checkerName': this.dataForm.checkerName,
                'creatorId': this.dataForm.creatorId
              })
            }).then((data) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
